package me.zxk.smartagriculture.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import me.zxk.smartagriculture.common.ApiResponse;
import me.zxk.smartagriculture.dto.comment.CommentRequest;
import me.zxk.smartagriculture.dto.comment.CommentResponse;
import me.zxk.smartagriculture.dto.news.NewsDetailResponse;
import me.zxk.smartagriculture.dto.news.NewsListResponse;
import me.zxk.smartagriculture.service.CommentService;
import me.zxk.smartagriculture.service.NewsService;
import me.zxk.smartagriculture.util.JwtUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

/**
 * 新闻控制器
 */
@Tag(name = "新闻管理", description = "新闻浏览、点赞、评论API")
@RestController
@RequestMapping("/api/news")
@RequiredArgsConstructor
public class NewsController {

    private final NewsService newsService;
    private final CommentService commentService;
    private final JwtUtil jwtUtil;

    /**
     * 获取新闻列表
     */
    @Operation(summary = "获取新闻列表", description = "分页获取新闻列表，支持关键词搜索")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "获取成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @GetMapping
    public ApiResponse<Page<NewsListResponse>> getNewsList(
            @Parameter(description = "页码，从0开始") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") int size,
            @Parameter(description = "排序字段") @RequestParam(defaultValue = "publishTime,desc") String sort,
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword,
            HttpServletRequest request) {
        try {
            // 解析排序参数
            String[] sortParams = sort.split(",");
            Sort.Direction direction = sortParams.length > 1 && "asc".equalsIgnoreCase(sortParams[1]) 
                    ? Sort.Direction.ASC : Sort.Direction.DESC;
            Pageable pageable = PageRequest.of(page, size, Sort.by(direction, sortParams[0]));
            
            // 获取当前用户ID（可能为null，表示未登录用户）
            Long currentUserId = getCurrentUserIdFromRequest(request);
            
            Page<NewsListResponse> news = newsService.getNewsList(keyword, pageable, currentUserId);
            return ApiResponse.success(news);
        } catch (Exception e) {
            return ApiResponse.error(400, e.getMessage());
        }
    }

    /**
     * 获取新闻详情
     */
    @Operation(summary = "获取新闻详情", description = "根据ID获取新闻详情，会增加浏览数")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "获取成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "404",
                    description = "新闻不存在",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @GetMapping("/{id}")
    public ApiResponse<NewsDetailResponse> getNewsDetail(
            @Parameter(description = "新闻ID") @PathVariable Long id,
            HttpServletRequest request) {
        try {
            // 获取当前用户ID（可能为null，表示未登录用户）
            Long currentUserId = getCurrentUserIdFromRequest(request);
            
            NewsDetailResponse news = newsService.getNewsDetail(id, currentUserId);
            return ApiResponse.success(news);
        } catch (Exception e) {
            return ApiResponse.error(404, e.getMessage());
        }
    }

    /**
     * 点赞/取消点赞新闻
     */
    @Operation(summary = "点赞新闻", description = "点赞或取消点赞新闻，需要登录")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "操作成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "401",
                    description = "未登录",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "404",
                    description = "新闻不存在",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @SecurityRequirement(name = "bearerAuth")
    @PostMapping("/{id}/like")
    public ApiResponse<Boolean> likeNews(
            @Parameter(description = "新闻ID") @PathVariable Long id,
            HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            boolean isLiked = newsService.toggleNewsLike(id, userId);
            String message = isLiked ? "点赞成功" : "取消点赞成功";
            return ApiResponse.success(message, isLiked);
        } catch (Exception e) {
            return ApiResponse.error(404, e.getMessage());
        }
    }

    /**
     * 获取新闻评论列表
     */
    @Operation(summary = "获取新闻评论", description = "分页获取新闻的评论列表")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "获取成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "404",
                    description = "新闻不存在",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @GetMapping("/{id}/comments")
    public ApiResponse<Page<CommentResponse>> getNewsComments(
            @Parameter(description = "新闻ID") @PathVariable Long id,
            @Parameter(description = "页码，从0开始") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "20") int size,
            @Parameter(description = "排序字段") @RequestParam(defaultValue = "createTime,desc") String sort,
            HttpServletRequest request) {
        try {
            // 解析排序参数
            String[] sortParams = sort.split(",");
            Sort.Direction direction = sortParams.length > 1 && "asc".equalsIgnoreCase(sortParams[1]) 
                    ? Sort.Direction.ASC : Sort.Direction.DESC;
            Pageable pageable = PageRequest.of(page, size, Sort.by(direction, sortParams[0]));
            
            // 获取当前用户ID（可能为null，表示未登录用户）
            Long currentUserId = getCurrentUserIdFromRequest(request);
            
            Page<CommentResponse> comments = commentService.getNewsComments(id, pageable, currentUserId);
            return ApiResponse.success(comments);
        } catch (Exception e) {
            return ApiResponse.error(404, e.getMessage());
        }
    }

    /**
     * 发表评论
     */
    @Operation(summary = "发表评论", description = "对新闻发表评论，需要登录")
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "评论成功",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "401",
                    description = "未登录",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "404",
                    description = "新闻不存在",
                    content = @Content(schema = @Schema(implementation = ApiResponse.class)))
    })
    @SecurityRequirement(name = "bearerAuth")
    @PostMapping("/{id}/comments")
    public ApiResponse<CommentResponse> postComment(
            @Parameter(description = "新闻ID") @PathVariable Long id,
            @Valid @RequestBody CommentRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromRequest(httpRequest);
            CommentResponse comment = commentService.postComment(id, userId, request);
            return ApiResponse.success("评论发表成功", comment);
        } catch (Exception e) {
            return ApiResponse.error(404, e.getMessage());
        }
    }

    /**
     * 获取当前用户ID（允许为null）
     */
    private Long getCurrentUserIdFromRequest(HttpServletRequest request) {
        try {
            String token = extractTokenFromRequest(request);
            if (token != null && jwtUtil.validateToken(token)) {
                return jwtUtil.getUserIdFromToken(token);
            }
        } catch (Exception e) {
            // 忽略异常，返回null表示未登录
        }
        return null;
    }

    /**
     * 从请求中获取用户ID（必须登录）
     */
    private Long getUserIdFromRequest(HttpServletRequest request) {
        String token = extractTokenFromRequest(request);
        if (token == null) {
            throw new RuntimeException("未登录");
        }
        return jwtUtil.getUserIdFromToken(token);
    }

    /**
     * 从请求中提取JWT Token
     */
    private String extractTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}
